package cn.linran.controller;

import cn.linran.domain.User;
import cn.linran.downgrade.DowngradeUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Value("${server.port}")
    private String port;
    @Value("${dynamicRefreshTest}")
    private String dynamicRefreshTest;
    /**
     * 提供一个根据Id返回User对象的接口，给order服务调用
     * @param id
     * @return
     */
    @GetMapping("/getById/{id}")
//    //资源限流
//    @SentinelResource(value="user-server-getById", blockHandler = "degradationMethod",blockHandlerClass = DowngradeUtil.class)
    //服务熔断降级
    @SentinelResource(value="user-server-getById", fallback = "fuseDegradation")
    public User getById(@PathVariable("id") Long id){
        //服务熔断降级
        try {
            // 用于让服务慢响应
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new User(id, "源码时代", "我在源码时代学习Java!，端口号：" + port+", dynamicRefreshTest："+dynamicRefreshTest);
    }
    /**
     * 方法一：资源限流本类降级
     */
//    public User degradationMethod(@PathVariable("id") Long id, BlockException e){
//        e.printStackTrace();
//        return new User(-1L, "服务降级触发！", "当前服务流量过大，请稍后重试！");
//    }

    /**
     * 熔断降级方法
     */
    public User fuseDegradation(@PathVariable("id") Long id, Throwable  e){
        e.printStackTrace();
        return new User(-1L, "熔断服务降级触发！", "服务不可用，请稍后重试！");
    }
}